﻿using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Word= Microsoft.Office.Interop.Word;
namespace DocPageCounter
{
    class PageCounter
    {
        /// <SUMMARY> 
        /// The main entry point for the application. 
        /// </SUMMARY> 
        [STAThread]
        
        static void Main(string[] args)
        {
            //Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();

            //// give any file name of your choice. 
            //object fileName = @"F:\Hoc\Projects\\MS Office Document Processing.docx";
            //object readOnly = false;
            //object isVisible = true;

            ////  the way to handle parameters you don't care about in .NET 
            //object missing = System.Reflection.Missing.Value;

            ////   Make word visible, so you can see what's happening 
            ////WordApp.Visible = true; 
            ////   Open the document that was chosen by the dialog 
            //Word.Document aDoc = WordApp.Documents.Open(ref fileName,
            //                        ref missing, ref readOnly, ref missing,
            //                        ref missing, ref missing, ref missing,
            //                        ref missing, ref missing, ref missing,
            //                         ref missing, ref isVisible);

            //Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
            //int num = aDoc.ComputeStatistics(stat, ref missing);
            //System.Console.WriteLine("The number of pages in doc is {0}",
            //                          num);
           
            //System.Console.ReadLine();
            string path = @"D:\Project\abc.docx";
            //Slitter(path);

            string strOrigFile = @"D:\Project\a.docx";
            string strCopiesDir = @"D:\Project\T";
            string strOutputDir = @"D:\Project\EDITabc.docx"; ;


            Splitv2(path);
            //Merge(strOrigFile, strCopiesDir, strOutputDir);
        }


        public static void Slitter(string path)
        {
            //Create a new instance of Word
            var app = new Word.Application();

            //Show the Word instance.
            //If the code runs too slowly, you can show the application at the end of the program
            //Make sure it works properly first; otherwise, you'll get an error in a hidden window
            //(If it still runs too slowly, there are a few other ways to reduce screen updating)
            app.Visible = false;

            //We need a reference to the source document
            //It should be possible to get a reference to an open Word document, but I haven't tried it
            var doc = app.Documents.Open(path);
            //(Can also use .docx)

            int pageCount = int.Parse(doc.Range().Information[Word.WdInformation.wdNumberOfPagesInDocument].ToString());

            //We'll hold the start position of each page here
            int pageStart = 0;

            object fileName = "";
            object readOnly = false;
            object isVisible = false;
           // object fileFormat = new object();
            //  the way to handle parameters you don't care about in .NET 
            object missing = System.Reflection.Missing.Value;


            for (int currentPageIndex = 1; currentPageIndex <= pageCount; currentPageIndex++)
            {
                //This Range object will contain each page.
                var page = doc.Range(pageStart);
                
                //Generally, the end of the current page is 1 character before the start of the next.
                //However, we need to handle the last page -- since there is no next page, the 
                //GoTo method will move to the *start* of the last page.
                if (currentPageIndex < pageCount)
                {
                    //page.GoTo returns a new Range object, leaving the page object unaffected
                    page.End = page.GoTo(
                        What: Word.WdGoToItem.wdGoToPage,
                        Which: Word.WdGoToDirection.wdGoToAbsolute,
                        Count: currentPageIndex + 1
                    ).Start-1;
                }
                else
                {
                    page.End = doc.Range().End;
                }
                pageStart = page.End + 1;

                //Copy and paste the contents of the Range into a new document
                //page.Select();
                //page.Copy();
                app.Selection.Copy();
                //page.Copy();
                var doc2 = app.Documents.Add();
                
                doc2.Range().Paste();


                //doc2.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary] = doc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
               // doc2.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "My Footer";
                object fileFormat = Word.WdSaveFormat.wdFormatDocument;
                //fileFormat = page.ParagraphFormat.KeepTogether;
                fileName = currentPageIndex.ToString();
                doc2.SaveAs(        ref fileName,
                                    ref fileFormat, ref readOnly, ref missing,
                                    ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing,
                                     ref missing, ref isVisible);
            }

            app.Quit(ref missing, ref missing, ref missing);
        }


        /// <summary>
        /// Merge a document with a set of copies
        /// </summary>
        /// <param name="strOrgDoc">
        /// Original file name
        /// </param>
        /// <param name="arrCopies">
        /// File names of the modified files
        /// </param>
        /// <param name="strOutDoc">
        /// The result filename
        /// </param>
        public static void Merge(string strOrgDoc, string[] arrCopies, string strOutDoc)
        {
            Word.Application objApp = null;

            //boxing of default values for COM interop purposes
            object objMissing = Missing.Value;
            object objFalse = false;
            object objTarget = Word.WdMergeTarget.wdMergeTargetSelected;
            object objUseFormatFrom = Word.WdUseFormattingFrom.wdFormattingFromSelected;

            try
            {
                objApp = new Word.Application();
                object objOrgDoc = strOrgDoc;

                Word.Document objDocLast = null;
                Word.Document objDocBeforeLast = null;

                objDocLast = objApp.Documents.Open(
                  ref objOrgDoc,    //FileName
                  ref objMissing,   //ConfirmVersions
                  ref objMissing,   //ReadOnly
                  ref objMissing,   //AddToRecentFiles
                  ref objMissing,   //PasswordDocument
                  ref objMissing,   //PasswordTemplate
                  ref objMissing,   //Revert
                  ref objMissing,   //WritePasswordDocument
                  ref objMissing,   //WritePasswordTemplate
                  ref objMissing,   //Format
                  ref objMissing,   //Enconding
                  ref objMissing,   //Visible
                  ref objMissing,   //OpenAndRepair
                  ref objMissing,   //DocumentDirection
                  ref objMissing,   //NoEncodingDialog
                  ref objMissing    //XMLTransform
                  );

                foreach (string strCopy in arrCopies)
                {
                    Debug.WriteLine("Merging file " + strCopy);
                    objDocLast.Merge(
                      strCopy,                //FileName    
                      ref objTarget,          //MergeTarget
                      ref objMissing,         //DetectFormatChanges
                      ref objUseFormatFrom,   //UseFormattingFrom
                      ref objMissing          //AddToRecentFiles
                      );
                    objDocBeforeLast = objDocLast;
                    objDocLast = objApp.ActiveDocument;
                    Debug.WriteLine("The active document is " + objDocLast.Name);

                    if (objDocBeforeLast != null)
                    {
                        Debug.WriteLine("Closing " + objDocBeforeLast.Name);
                        objDocBeforeLast.Close(
                          ref objFalse,     //SaveChanges
                          ref objMissing,   //OriginalFormat
                          ref objMissing    //RouteDocument
                          );
                    }


                }

                object objOutDoc = strOutDoc;

                objDocLast.SaveAs(
                  ref objOutDoc,      //FileName
                  ref objMissing,     //FileFormat
                  ref objMissing,     //LockComments
                  ref objMissing,     //PassWord     
                  ref objMissing,     //AddToRecentFiles
                  ref objMissing,     //WritePassword
                  ref objMissing,     //ReadOnlyRecommended
                  ref objMissing,     //EmbedTrueTypeFonts
                  ref objMissing,     //SaveNativePictureFormat
                  ref objMissing,     //SaveFormsData
                  ref objMissing,     //SaveAsAOCELetter,
                  ref objMissing,     //Encoding
                  ref objMissing,     //InsertLineBreaks
                  ref objMissing,     //AllowSubstitutions
                  ref objMissing,     //LineEnding
                  ref objMissing      //AddBiDiMarks
                  );

                foreach (Word.Document objDocument in objApp.Documents)
                {
                    objDocument.Close(
                      ref objFalse,     //SaveChanges
                      ref objMissing,   //OriginalFormat
                      ref objMissing    //RouteDocument
                      );
                }

            }
            finally
            {
                objApp.Quit(
                  ref objMissing,     //SaveChanges
                  ref objMissing,     //OriginalFormat
                  ref objMissing      //RoutDocument
                  );
                objApp = null;
            }
        }

        /// <summary>
        /// Merge a document with a set of copies
        /// </summary>
        /// <param name="strOrgDoc">
        /// Original file name
        /// </param>
        /// <param name="strCopyFolder">
        /// Folder in which the copies are located
        /// </param>
        /// <param name="strOutDoc">
        /// The result filename
        /// </param>
        public static void Merge(string strOrgDoc, string strCopyFolder, string strOutDoc)
        {
            string[] arrFiles = Directory.GetFiles(strCopyFolder);
            Merge(strOrgDoc, arrFiles, strOutDoc);
        }

        public static void Splitv2(string path)
        {
            Word.Application WordApp = new Word.Application();
            Word.Document BaseDoc = new Word.Document();
            Word.Document DestDoc = new Word.Document(); 
            int intNumberOfPages;
            string intNumberOfChars;
            int intPage;
            // Word Constants
            const int wdGoToPage = 1;
            const int wdStory = 6;
            const int wdExtend = 1;
            const int wdCharacter = 1;
            // Show WordApp
            WordApp.ShowMe();
            // Load Base Document
            BaseDoc = WordApp.Documents.Open(path);
            BaseDoc.Repaginate();
            // Loop through pages
            intNumberOfPages = BaseDoc.BuiltInDocumentProperties["Number of Pages"].value;
            intNumberOfChars = BaseDoc.BuiltInDocumentProperties["Number of Characters"].ToString();
            for (intPage = 1; (intPage <= intNumberOfPages); intPage++)
            {
                if ((intPage == intNumberOfPages))
                {
                    WordApp.Selection.EndKey(wdStory);
                }
                else
                {
                    WordApp.Selection.GoTo(wdGoToPage, 2);
                   
                    WordApp.Selection.MoveLeft(wdCharacter, 1);
                    // TODO: Labeled Arguments not supported. Argument: 1 := 'Unit'
                    // TODO: Labeled Arguments not supported. Argument: 2 := 'Count'
                }
               
                WordApp.Selection.HomeKey(wdStory, wdExtend);
            
                WordApp.Selection.Copy();
            
                // Create New Document
                DestDoc = WordApp.Documents.Add();
                DestDoc.Activate();
                WordApp.Selection.Paste();
                DestDoc.SaveAs(("NewFileName" + (intPage.ToString() + ".doc")));
                DestDoc.Close();
                DestDoc = null;
                WordApp.Selection.GoTo(wdGoToPage, 2);
             
                WordApp.Selection.HomeKey(wdStory, wdExtend);
                WordApp.Selection.Delete();
            }
            BaseDoc.Close(false);
            BaseDoc = null;
            WordApp.Quit();
            WordApp = null;

        }
    }
}

